export type DeepseekMessage = { role: 'system' | 'user' | 'assistant'; content: string };

export async function callDeepseek(params: {
  apiKey: string; // your apikey: Authorization: Bearer <apikey>
  model?: string; // e.g., 'deepseek-r1-250120'
  messages: DeepseekMessage[];
  appId?: string;
  appSecret?: string;
}): Promise<string> {
  const body: any = {
    model: params.model ?? 'deepseek-r1-250120',
    messages: params.messages,
    stream: false,
  };

  const res = await fetch('/deepseek', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${params.apiKey}`,
      ...(params.appId ? { 'X-App-Id': params.appId } : {}),
      ...(params.appSecret ? { 'X-App-Secret': params.appSecret } : {}),
    },
    body: JSON.stringify(body),
  });

  const textBody = await res.text();
  if (!res.ok) {
    throw new Error(`DeepSeek HTTP ${res.status}: ${textBody || '(empty body)'}`);
  }
  try {
    const data = JSON.parse(textBody);
    return data?.choices?.[0]?.message?.content ?? '';
  } catch {
    return textBody;
  }
}


